package com.shigu.component.shiro.filter;

import com.shigu.mo.enums.SessionEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Service("wx_login_filter")
public class WxLoginFilter implements Filter {

    @Value("${wechat.appid}")
    private String APP_ID;

    @Value("${wechat.appsecret}")
    private String APP_SECRET;

    @Value("${main_host}")
    private String MAIN_HOST;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest= (HttpServletRequest) request;
//        servletRequest.getSession().setAttribute(SessionEnum.WX_LOGEDUSER.toString(),"oitinxKppMQ8C5ovBLBoiZwUak7M");
        String openid= (String) servletRequest.getSession().getAttribute(SessionEnum.WX_LOGEDUSER.toString());
        if (openid == null) {
            String url=servletRequest.getRequestURL().toString();
            if (url.endsWith(".json")) {
                chain.doFilter(request,response);
            }
            String queryString=servletRequest.getQueryString();
            String backUrl= URLEncoder.encode(url+
                    (queryString==null?"":("?"+queryString)), "utf-8").replace("%","!");
            //跳静默登陆
            String redirect="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APP_ID +
                    "&redirect_uri="+MAIN_HOST+"wxlogin.htm&response_type=code&scope=snsapi_base" +
                    "&state="+ (StringUtils.isEmpty(backUrl)?"":URLEncoder.encode(backUrl,"utf-8"));
            HttpServletResponse servletResponse= (HttpServletResponse) response;
            servletResponse.sendRedirect(redirect);
        }else{
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
